package cn.aitrox.ry.service.anno.remote.imageService;

import cn.aitrox.ry.common.bean.JsonCallback;
import cn.aitrox.ry.service.anno.config.AnnoNacosProperties;
import cn.aitrox.ry.service.anno.remote.imageService.dto.ImageServiceReqDataDto;
import cn.aitrox.ry.service.anno.remote.imageService.dto.ImageServiceReqDto;
import cn.aitrox.ry.util.JSONUtil;
import cn.aitrox.ry.util.NetUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class ImageServiceApiImpl implements ImageServiceApi {

    @Value("${imageService.url}")
    private String url;

    @Autowired
    private AnnoNacosProperties nacosProp;

    @Override
    public <T> T doRequest(ImageServiceReqDataDto reqDataDto, ImageServiceMethodEnum methodEnum, JsonCallback<T> jsonCallback) throws IOException {
        Integer connectTimeout = nacosProp.getHttpClientConnectTimeout();
        Integer socketTimeout = nacosProp.getHttpClientSocketTimeout();
        String reqJson = JSONUtil.toJson(new ImageServiceReqDto<>(methodEnum.getMethod(), reqDataDto), ImageServiceReqDto.class);
        return this.doRequest(url, methodEnum, reqJson, jsonCallback, connectTimeout, socketTimeout);
    }


    private <T> T doRequest(String url, ImageServiceMethodEnum methodEnum, String reqJson, JsonCallback<T> jsonCallback, Integer connectTimeout, Integer socketTimeout) throws IOException {
        String responseStr;
        if (null != connectTimeout || null != socketTimeout) {
            responseStr = NetUtil.httpPostString(url, reqJson, null, "application/json", methodEnum.getDesc(), connectTimeout, socketTimeout);
        } else {
            responseStr = NetUtil.httpPostString(url, reqJson, null, "application/json", methodEnum.getDesc(), 3000, 300000);
        }
        return jsonCallback.deserializer(responseStr);
    }
}
